package com.enjoy.thyou.config;

import com.enjoy.thyou.annotation.BeansScanner;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.util.StringUtils;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;

public class BeansScannerRegistrar implements ImportBeanDefinitionRegistrar {
	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
		boolean acceptAllBeans = true;
		AnnotationAttributes attributes = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(BeansScanner.class.getName()));
		BeanPackageScanner scanner = new BeanPackageScanner(registry);
		Class<? extends Annotation> annotationClass = attributes.getClass("annotationClass");
		if (!Annotation.class.equals(annotationClass)){
			acceptAllBeans = false;
			scanner.addIncludeFilter(new AnnotationTypeFilter(annotationClass));
		}

		List<String> backPackages = new ArrayList<>();
		for (String pkg : attributes.getStringArray("value")) {
			if (StringUtils.hasText(pkg)){
				backPackages.add(pkg);
			}
		}

		for (String pkg : attributes.getStringArray("basePackages")) {
			if (StringUtils.hasText(pkg)){
				backPackages.add(pkg);
			}
		}

		if (acceptAllBeans){
			scanner.addIncludeFilter((metadataReader, metadataReaderFactory) -> {
				return true;
			});
		}
		scanner.doScan(StringUtils.toStringArray(backPackages));
	}
}
